package thread;

import java.util.PriorityQueue;

//任务
class Task implements Comparable<Task>{
    private Runnable r;
    private long delay;
    public Task(Runnable r, long delay) {
        this.r = r;
        this.delay = delay;
    }

    public void run() {
        r.run();
    }
    @Override
    public int compareTo(Task o) {
        return (int)(this.delay - o.delay);
    }

    public long getDelay() {
        return this.delay;
    }
}

class MyTimer1 {
    //锁对象
    private final Object locker = new Object();

    //优先级队列，可对任务进行排序
    private PriorityQueue<Task> queue = new PriorityQueue<>();

    public MyTimer1() {
        Thread t = new Thread(() -> {
            try {
                while (true) {
                    synchronized (locker) {
                        //如果队列为空则阻塞
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        //拿出队列中优先级最高的任务
                        Task task = queue.peek();
                        //判断当前时刻是否能执行当前任务
                        if (task.getDelay() > System.currentTimeMillis()) {
                            locker.wait(task.getDelay() - System.currentTimeMillis());
                        } else {
                            task.run();
                            //删除已经执行完毕的任务
                            queue.poll();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
    }

    public void schedule(Runnable r, long delay) {
        synchronized (locker) {
            Task task = new Task(r, System.currentTimeMillis()+delay);
            queue.offer(task);
            locker.notify();
        }

    }
}


public class Demo61 {
    public static void main(String[] args) {
        MyTimer1 timer1 = new MyTimer1();
        timer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello5");
            }
        }, 5000);
        timer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello1");
            }
        }, 1000);
        timer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello3");
            }
        }, 3000);
        timer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello8");
            }
        }, 8000);
    }
}
